import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'contactor_reducer.dart';
import '../utils/upload_service.dart';

import 'contactor_action.dart';
import 'contactor_middleware.dart';
import 'contactor_state.dart';

class ContactorPage extends StatelessWidget {
  ContactorPage({Key? key}) : super(key: key);

  final Store<ContactorState> store = Store(
    contactorReducer,
    initialState: ContactorState.initial(),
    middleware: [
      fetchContactorMiddleware,
    ],
  );

  @override
  Widget build(BuildContext context) {
    return StoreProvider<ContactorState>(
      store: store,
      child: Scaffold(
        appBar: AppBar(
          title: Text('联系人'),
          brightness: Brightness.dark,
        ),
        body: StoreConnector<ContactorState, _ViewModel>(
          converter: (Store<ContactorState> store) => _ViewModel.create(store),
          builder: (BuildContext context, _ViewModel viewModel) {
            return EasyRefresh(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return ListTile(
                    leading:
                        _getRoundImage(viewModel.contactors[index].avatar, 50),
                    title: Text(viewModel.contactors[index].nickname),
                    subtitle: Text(
                      viewModel.contactors[index].description,
                      style: TextStyle(fontSize: 14.0, color: Colors.grey),
                    ),
                  );
                },
                itemCount: viewModel.contactors.length,
              ),
              onRefresh: () async {
                store.dispatch(RefreshAction());
              },
              onLoad: () async {
                store.dispatch(LoadAction());
              },
              firstRefresh: true,
            );
          },
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: () {
            store.dispatch(RefreshAction());
          },
        ),
      ),
    );
  }

  Widget _getRoundImage(String imageUrl, double size) {
    return Container(
      width: size,
      height: size,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(size / 2)),
      ),
      child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.fill),
    );
  }
}

class _ViewModel {
  final List<_ContactorViewModel> contactors;

  _ViewModel(this.contactors);

  factory _ViewModel.create(Store<ContactorState> store) {
    List<_ContactorViewModel> items = store.state.contactors
        .map((dynamic item) => _ContactorViewModel.fromJson(item))
        .toList();

    return _ViewModel(items);
  }
}

class _ContactorViewModel {
  final String followedUserId;
  final String nickname;
  final String avatar;
  final String description;

  _ContactorViewModel({
    required this.followedUserId,
    required this.nickname,
    required this.avatar,
    required this.description,
  });

  static _ContactorViewModel fromJson(Map<String, dynamic> json) {
    return _ContactorViewModel(
        followedUserId: json['followedUserId'],
        nickname: json['nickname'],
        avatar: UploadService.uploadBaseUrl + 'image/' + json['avatar'],
        description: json['description']);
  }
}
